package com.code.qgjx.controller.dealcontroller;

import com.alibaba.fastjson.JSON;
import com.code.qgjx.entity.JobPosition;
import com.code.qgjx.entity.StudentJob;
import com.code.qgjx.service.JobPositionService;
import com.code.qgjx.service.StudentJobService;
import com.code.qgjx.tools.Layui;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 控制器类，用于处理与岗位相关的请求
 */
@RestController
@RequestMapping("/Sys/job")
public class JobPositionController {

    /**
     * 用于处理岗位相关的业务逻辑
     */
    @Autowired
    private JobPositionService jobPositionService;

    /**
     * 用于处理学生岗位申请相关的业务逻辑
     */
    @Autowired
    private StudentJobService studentJobService;

    /**
     * 获取岗位列表
     *
     * @param keyword 搜索关键字
     * @param page 当前页码
     * @param limit 每页条数
     * @param status 岗位状态
     * @param session HTTP会话
     * @return 返回岗位列表的JSON数据
     */
    @GetMapping("/list")
    public Object getJobList(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(required = false) String status, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取总数和分页数据
            int total = jobPositionService.getJobCount(keyword,status);
            // 计算偏移量
            int offset = (page - 1) * limit;
            List<JobPosition> list = jobPositionService.getJobList(keyword, offset, limit,status);
            for (JobPosition job : list) {
                Integer jid = job.getId();
                Long uId = (Long)session.getAttribute("id");
                StudentJob studentJob = studentJobService.getStudentJob(Long.valueOf(uId), Long.valueOf(jid));
                if (studentJob != null){
                    int jobStatus = studentJob.getStatus();
                    if (jobStatus == 0){
                        status = "已申请";
                    }else if (jobStatus == 1){
                        status = "已通过";
                    }else {
                        status = "已驳回";
                    }
                }else {
                    status = "";
                }
                job.setStatus(status);
            }
            Layui l = Layui.data(total, list);
            return JSON.toJSON(l);

        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 1);
            result.put("msg", "获取岗位列表失败");
            result.put("count", 0);
            result.put("data", null);
        }


        return result;
    }

    /**
     * 根据用户获取岗位列表
     *
     * @param keyword 搜索关键字
     * @param page 当前页码
     * @param limit 每页条数
     * @param user 用户名
     * @return 返回用户相关的岗位列表的JSON数据
     */
    @GetMapping("/listByUser")
    public Object listByUser(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit, @RequestParam(required = true) String user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 获取总数和分页数据
            int total = jobPositionService.getJobCountByUser(user);
            // 计算偏移量
            int offset = (page - 1) * limit;
            List<JobPosition> list = jobPositionService.getJobListByUser(keyword, offset, limit,user);
            Layui l = Layui.data(total, list);
            return JSON.toJSON(l);

        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "获取岗位列表失败");
            result.put("count", 0);
            result.put("data", null);
        }


        return result;
    }

    /**
     * 获取岗位详情
     *
     * @param id 岗位ID
     * @return 返回岗位详情的JSON数据
     */
    @GetMapping("/detail/{id}")
    public Map<String, Object> getJobDetail(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            JobPosition job = jobPositionService.getJobDetail(id);
            result.put("code", 0);
            result.put("data", job);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "获取岗位详情失败");
        }
        return result;
    }

    /**
     * 审批岗位
     *
     * @param id 岗位ID
     * @param session HTTP会话
     * @return 返回审批结果的JSON数据
     */
    @PostMapping("/approve/{id}")
    public Map<String, Object> approveJob(@PathVariable Integer id, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            String updatedBy = session.getAttribute("account").toString();
            if (jobPositionService.approveJob(id, updatedBy)) {
                result.put("code", 0);
                result.put("msg", "审批通过成功");
            } else {
                result.put("code", 1);
                result.put("msg", "审批通过失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "审批通过失败");
        }
        return result;
    }

    /**
     * 驳回岗位申请
     *
     * @param id 岗位ID
     * @param rejectReason 驳回原因
     * @param session HTTP会话
     * @return 返回驳回结果的JSON数据
     */
    @PostMapping("/reject/{id}")
    public Map<String, Object> rejectJob(@PathVariable Integer id,
                                       @RequestParam String rejectReason,
                                       HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            String updatedBy = session.getAttribute("account").toString();
            if (jobPositionService.rejectJob(id, rejectReason, updatedBy)) {
                result.put("code", 0);
                result.put("msg", "驳回成功");
            } else {
                result.put("code", 1);
                result.put("msg", "驳回失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "驳回失败");
        }
        return result;
    }

    /**
     * 添加新岗位
     *
     * @param map 岗位信息的键值对
     * @param session HTTP会话
     * @return 返回添加结果的JSON数据
     */
    @PostMapping("/add")
    @ResponseBody
    public Map<String, Object> addJob(@RequestBody Map<String, Object> map, HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        try {
            JobPosition jobPosition = new JobPosition();
            jobPosition.setDepartmentName(map.get("departmentName").toString());
            jobPosition.setLocation(map.get("location").toString());
            jobPosition.setJobType(map.get("jobType").toString());
            jobPosition.setSupervisor(map.get("supervisor").toString());
            jobPosition.setContactPhone(map.get("contactPhone").toString());
            jobPosition.setWorkingHours(map.get("workingHours").toString());
            jobPosition.setSalary(map.get("salary").toString());
            jobPosition.setHeadcount(Integer.parseInt(map.get("headcount").toString()));
            jobPosition.setStatus("待审批");
            jobPosition.setCreatedBy(session.getAttribute("id").toString());

            if (jobPositionService.addJob(jobPosition)) {
                result.put("code", 0);
                result.put("msg", "发布成功");
            } else {
                result.put("code", 1);
                result.put("msg", "发布失败");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "发布失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 获取用户岗位列表
     *
     * @param userId 用户ID
     * @return 返回用户岗位列表的JSON数据
     */
    @RequestMapping("/getUserJobPositions")
    @ResponseBody
    public Map<String, Object> getUserJobPositions(@RequestParam("userId") Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<JobPosition> positions = jobPositionService.getJobPositionsByUserId(userId);
            result.put("code", 0);
            result.put("data", positions);
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "获取岗位列表失败");
        }
        return result;
    }

    /**
     * 获取岗位对应的教师ID
     *
     * @param jobPositionId 岗位ID
     * @return 返回教师ID的JSON数据
     */
    @GetMapping("/getTeacherId")
    @ResponseBody
    public Map<String, Object> getTeacherId(@RequestParam("jobPositionId") Long jobPositionId) {
        Map<String, Object> result = new HashMap<>();
        try {
            JobPosition jobPosition = jobPositionService.getJobDetail(jobPositionId.intValue());
            if (jobPosition != null) {
                result.put("code", 0);
                result.put("teacherId", jobPosition.getCreatedBy());
            } else {
                result.put("code", 1);
                result.put("msg", "岗位不存在");
            }
        } catch (Exception e) {
            result.put("code", 1);
            result.put("msg", "获取教师ID失败");
        }
        return result;
    }
}
